package com.googlecode.ebasys.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;

import com.googlecode.ebasys.dao.UserDao;
import com.googlecode.ebasys.entity.User;

/**
 * Controller for debugging purposes
 * 
 * Used for development / integration testing
 *
 * @author Tomas Varaneckas
 * @version $Id: DebugController.java 59 2009-02-09 16:45:24Z tomas.varaneckas $
 */
public class DebugController extends BaseController {

    @Autowired
    private UserDao userService;
    
    @Override
    protected void handleRequest(ModelAndView mav, HttpServletRequest request,
            HttpServletResponse response) {
        if (request.getMethod().equalsIgnoreCase("post")) {
            User toSave = new User();
            try {
                String id = ServletRequestUtils.getStringParameter(request, "id");
                if (!id.equals("")) {
                    toSave.setId(Long.valueOf(id));
                }
                toSave.setUserName(ServletRequestUtils
                        .getStringParameter(request, "userName"));
                toSave.setFullName(ServletRequestUtils
                        .getStringParameter(request, "fullName"));
                toSave.setEmail(ServletRequestUtils
                        .getStringParameter(request, "email"));
                boolean saved = userService.save(toSave);
                mav.addObject("saved", saved ? "saved: yes" : "saved: no");
            } catch (ServletRequestBindingException e) {
                throw new RuntimeException("doono", e);
            }
        }

        long id = ServletRequestUtils.getLongParameter(request, "id", 0L);
        if (id > 0) {
            User user = userService.findById(id);
            logger.info("Found user: " + user);
            mav.addObject("debug_user", user == null ? new User() : user);
        } else {
            mav.addObject("debug_user", new User());
        }
        mav.addObject("all_users", userService.findAll());
    }

}
